const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
// 引入配置文件
require("dotenv").config();
// 导入跨域中间件
const cors = require("cors");

// 引入首页路由
const indexRouter = require("./routes/index");
// 引入用户权限路由
const authRouter = require("./routes/admin/auth");
// 引入柱状图路由
const bardataRouter = require("./routes/admin/bardata");
// 引入各类销售情况
const productsalesRouter = require("./routes/admin/productsales");
// 引入水位图路由
const waterlevelRouter = require("./routes/admin/waterlevel");
// 引入退回率路由
const returnrateRouter = require("./routes/admin/returnrate");
// 引入雷达图数据
const redarechartRouter = require("./routes/admin/redarechart");
// 引入各平台销售情况
const platformcomRoute = require("./routes/admin/platform");
// 引入电商指标路由
const coreindicatorsRouter = require("./routes/admin/coreindicators");
// 引入地图数据路由
const chinamapRouter = require("./routes/admin/chinamap");

const app = express();
// const expressJWT = require("express-jwt");
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors());
// 限制有效接口
// app.use(expressJWT({ secret: process.env.SECRET }).unless({ path: [/^\/api\//] }))

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/api", authRouter);
app.use("/bardata", bardataRouter);
app.use("/productsale", productsalesRouter);
app.use("/waterlevel", waterlevelRouter);
app.use("/returnrate", returnrateRouter);
app.use("/redarechart", redarechartRouter);
app.use("/platformcom", platformcomRoute);
app.use("/coreindicators", coreindicatorsRouter);
app.use("/chinamap", chinamapRouter);

app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // token过期或无效,则返回
  if (err.name == "UnauthorizedError") {
    return res.status(401).json("身份认证失败!");
  }
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
